
package com.scalar.chiptrack.users.actions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Location;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.chiptrack.users.forms.AdapterSetupForm;

public final class AdapterSetupAction extends ChipTrackAction {


    // ----------------------------------------------------- Instance Variables
           

    // --------------------------------------------------------- Public Methods

	public ActionForward execute(ActionMapping mapping,
				 ActionForm form,
				 HttpServletRequest request,
				 HttpServletResponse response)
	throws Exception
	{
		// Extract attributes and parameters we will need
		AdapterSetupForm subform = (AdapterSetupForm) form;
		String action = request.getParameter("action");
		//system.out.println("In the action" + action);
		// Validate the request parameters specified by the user
		HashMap errors = new HashMap();
		               
		if("save".equals(action))
		{
			//here using the property utils we can get the form value
			String [] fabVendor             = subform.getSelectedFabLocations();
			String [] waferStoreVendor      = subform.getSelectedWaferStoreLocations();
			String [] sortVendor            = subform.getSelectedSortLocations();
			String [] dieBankVendor         = subform.getSelectedDieBankLocations();
			String [] AssemblyVendor        = subform.getSelectedAssemblyLocations();
			String [] TestVendor            = subform.getSelectedTestLocations();
			String [] classStoreVendor      = subform.getSelectedClassStoreLocations();
			String [] markAndPackVendor     = subform.getSelectedMarkAndPackLocations();
			String [] finishedGoodsVendor   = subform.getSelectedFinishedGoodsLocations();
			
			ArrayList locationIdList = new ArrayList();                        
				
			if(fabVendor!=null)
				loadVendorIdList(fabVendor,locationIdList);
			if(waferStoreVendor!=null)
				loadVendorIdList(waferStoreVendor,locationIdList);
			if(sortVendor!=null)
				loadVendorIdList(sortVendor,locationIdList);
			if(dieBankVendor!=null)
				loadVendorIdList(dieBankVendor,locationIdList);
			if(AssemblyVendor!=null)
				loadVendorIdList(AssemblyVendor,locationIdList);
			if(TestVendor!=null)
				loadVendorIdList(TestVendor,locationIdList);
			if(classStoreVendor!=null)
				loadVendorIdList(classStoreVendor,locationIdList);
			if(markAndPackVendor!=null)
				loadVendorIdList(markAndPackVendor,locationIdList);
			if(finishedGoodsVendor!=null)
				loadVendorIdList(finishedGoodsVendor,locationIdList);
		   
			//vendorIdList = removeDuplicates(vendorIdList);                        
			DBTransaction dbTransaction = null; 
			boolean success =false;

			try
			{
				
				dbTransaction = DBTransaction.getInstance();
				dbTransaction.begin();
				AdaptorSetUpDAO.saveVendorAdaptorSetup(dbTransaction,locationIdList);
						
				/*
				if(fabVendor!=null)
				AdaptorSetUpDAO.saveAdaptorInfo(dbTransaction,fabVendor,"Fab");
				if(waferStoreVendor!=null)
				AdaptorSetUpDAO.saveAdaptorInfo(dbTransaction,waferStoreVendor,"Wafer Store");
				if(sortVendor!=null)
				AdaptorSetUpDAO.saveAdaptorInfo(dbTransaction,sortVendor,"Sort");	
				if(dieBankVendor!=null)
				AdaptorSetUpDAO.saveAdaptorInfo(dbTransaction,dieBankVendor,"Die Bank");	
				if(AssemblyVendor!=null)
				AdaptorSetUpDAO.saveAdaptorInfo(dbTransaction,AssemblyVendor,"Assembly");	
				if(TestVendor!=null)
				AdaptorSetUpDAO.saveAdaptorInfo(dbTransaction,TestVendor,"Test");	
				if(classStoreVendor!=null)
				AdaptorSetUpDAO.saveAdaptorInfo(dbTransaction,classStoreVendor,"Class Store");	
				if(markAndPackVendor!=null)
				AdaptorSetUpDAO.saveAdaptorInfo(dbTransaction,markAndPackVendor,"Mark & Pack");	
				if(finishedGoodsVendor!=null)
				AdaptorSetUpDAO.saveAdaptorInfo(dbTransaction,finishedGoodsVendor,"Finished Goods");*/	
				success = true;
			}
			catch ( Throwable t )
			{
				t.printStackTrace();
				errors.put ("Internal Server Error", "Could not save Vendor Adaptor Information");
				request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
			}
			finally
			{
			// Rollback or Commit the Transaction
				if (success == true)
				{
					dbTransaction.commit();
				}
				else
				{
					dbTransaction.rollback();
				}
			}

			if ( success == false )
			{
				return (mapping.findForward ("failure"));
			}
                                                
			request.setAttribute("vendorList",loadVendorAdaptors(AdaptorSetUpDAO.getVendorAdaptor().iterator()));
			return (mapping.findForward("next"));
		}
		else
		{
			//This method is added by Bhaskar on 22 october 2003
			//fetches all the records that 
			request.setAttribute ( "allCheckedLocations", VendorDAO.getCheckedLocations () );
			request.setAttribute("fabLocations",VendorDAO.getFabLocations());
			request.setAttribute("waferStoreLocations",VendorDAO.getWaferStoreLocations());
			request.setAttribute("sortLocations",VendorDAO.getSortLocations());
			request.setAttribute("dieBankLocations",VendorDAO.getDieBankLocations());
			request.setAttribute("assemblyLocations",VendorDAO.getAssemblyLocations());
			request.setAttribute("classStoreLocations",VendorDAO.getClassStoreLocations());
			request.setAttribute("testLocations",VendorDAO.getTestLocations());
			request.setAttribute("markAndPackLocations",VendorDAO.getMarkAndPackLocations());
			request.setAttribute("finishedGoodsLocations",VendorDAO.getFinishedGoodsLocations());
			/*
			String [] selectedLocations = AdaptorSetUpDAO.getAdaptorInfo();
			request.setAttribute("selectedLocations", selectedLocations);
						
			subform.setSelectedFabLocations(selectedLocations);
			subform.setSelectedWaferStoreLocations(selectedLocations);
			subform.setSelectedSortLocations(selectedLocations);
			subform.setSelectedDieBankLocations(selectedLocations);
			subform.setSelectedAssemblyLocations(selectedLocations);
			subform.setSelectedTestLocations(selectedLocations);
			subform.setSelectedClassStoreLocations(selectedLocations);
			subform.setSelectedMarkAndPackLocations(selectedLocations);
			subform.setSelectedFinishedGoodsLocations(selectedLocations);
			*/
			request.setAttribute("adapterSetupForm",subform);

		}
		
		// Report any errors we have discovered back to the original form
		 if(!errors.isEmpty()) 
			 request.setAttribute(SessionKeys.MESSAGES, errors);
		
		//Please look at this return later(Where do we need this retrurned) ????
		return (mapping.findForward("success"));
	}

	private static ArrayList loadVendorLocations(Iterator locs) throws ScalarException
	{
		ArrayList locations = new ArrayList();
        
        //Iterator locs = vendorLocations.iterator();
        while(locs.hasNext())
		{
            VendorLocation location = (VendorLocation) locs.next();
            //System.out.println("Location Id"+ location.getLocationName() + "  "+ location.getLocationID());
            locations.add(new org.apache.struts.util.LabelValueBean(
                                 location.getLocationName(), location.getLocationID()));
        }
        
        return locations;
	}

	private static ArrayList loadVendorAdaptors(Iterator locs) throws ScalarException
	{
        ArrayList vendorList = new ArrayList();
        
        //Iterator locs = vendorLocations.iterator();
        while(locs.hasNext()) {
            Location location = (Location) locs.next();
            //System.out.println("Location Id"+ location.getLocationName() + "  "+ location.getLocationID());
            vendorList.add(new org.apache.struts.util.LabelValueBean(
				 location.getVendorName(),new Integer(location.getLocationId()).toString()));
        }
        
        return vendorList;
	}
   
   /*
    private static ArrayList loadVendorIdList(String [] vendor,ArrayList vendorList) throws ScalarException
   {
        for(int i=0;i<vendor.length;i++){
            vendorList.add(vendor[i]);
        }
            
        return vendorList;
   }
   */
	private static ArrayList loadVendorIdList(String [] vendor,ArrayList vendorList) throws ScalarException
	{
		String vendorString = vendor[0];
		//system.out.println("vendorString"+vendorString);
		StringTokenizer st = new StringTokenizer(vendorString, ",");
		
		while (st.hasMoreTokens()) {
			String tok = st.nextToken();
			vendorList.add(tok);
		}
	    return vendorList;
	}
   
	private static ArrayList  removeDuplicates ( ArrayList list )
	{
      Collection collect = new HashSet(list);
      
      return new ArrayList(collect);
          // if current element is a duplicate, iter.remove();// remove it    }  }
	}
}
